package dev.mcdd.user.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dev.mcdd.common.constant.RoleType;
import dev.mcdd.user.entity.Permission;
import dev.mcdd.user.entity.Role;
import dev.mcdd.user.entity.User;
import dev.mcdd.user.exception.RoleNotfoundException;
import dev.mcdd.user.mapper.RoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * RoleServiceImpl
 *
 * @author: mcdd1024
 * @date 2025/1/16 05:29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper mapper;
    private final PermissionService permissionService;

    @Override
    public User authorizationUserRole(User user, RoleType type) {
        Long userId = user.getId();
        if (userId == null) {
            throw new IllegalArgumentException("userId is null");
        }
        List<Permission> permissions;
        Role.RoleBuilder builder = Role.builder();
        switch (type) {
            case USER -> {
                if (mapper.saveUserRoleByUserId(userId) == 0) {
                    throw new RuntimeException(String.format("saved user role failure for userId %s", userId));
                }
                permissions = permissionService.loadPermissionsByRoleId(RoleType.USER.getId());
                builder
                    .id(RoleType.USER.getId())
                    .name(RoleType.USER.name())
                    .code(RoleType.USER.getCode())
                    .permissions(permissions);

            }
            case ADMIN -> {
                if (mapper.saveAdminRoleByUserId(userId) == 0) {
                    throw new RuntimeException(String.format("saved admin role failure for userId %s", userId));
                }
                permissions = permissionService.loadPermissionsByRoleId(RoleType.ADMIN.getId());
                builder
                    .id(RoleType.ADMIN.getId())
                    .name(RoleType.ADMIN.name())
                    .code(RoleType.ADMIN.getCode())
                    .permissions(permissions);
            }
            default -> throw new IllegalArgumentException("role type not supported");
        }
        user.setRole(builder.build());
        return user;
    }

    @Override
    public Role loadRoleByUserId(Long userId) {
        if (userId == null) {
            throw new IllegalArgumentException("userId is null");
        }
        Role role = mapper.selectRoleByUserId(userId);
        if (role == null) {
            throw new RoleNotfoundException(String.format("Role with userId %s not found", userId));
        }
        Integer roleId = role.getId();
        List<Permission> permissions = permissionService.loadPermissionsByRoleId(roleId);
        role.setPermissions(permissions);
        return role;
    }

}
